<template>
  <div>
    <PhotoListBG />
    <div class="photo-manager">
      <div class="upload-container">
        <!-- 我要上传按钮 -->
        <el-button
          type="primary"
          @click="showUploadDialog = true"
          color="#f1e69c"
        >
          我要上传
        </el-button>

        <!-- 上传图片表单弹窗 -->
        <el-dialog
          v-model="showUploadDialog"
          title="上传图片"
          width="40%"
          :before-close="handleDialogClose"
        >
          <el-form :model="uploadForm" label-width="80px">
            <!-- 图片标题 -->
            <el-form-item label="图片标题">
              <el-input
                v-model="uploadForm.title"
                placeholder="请输入图片标题"
              />
            </el-form-item>

            <!-- 图片分类 -->
            <el-form-item label="图片分类">
              <el-select v-model="uploadForm.category" placeholder="请选择分类">
                <el-option
                  v-for="item in categories"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <!-- 图片上传 -->
            <el-form-item label="图片文件">
              <el-upload
                class="custom-upload-box"
                drag
                :before-upload="beforeUpload"
                :file-list="fileList"
                :on-change="handleChange"
                :on-preview="handlePreview"
                list-type="picture-card"
                auto-upload="false"
                multiple
                :limit="1"
              >
                <el-icon><upload-filled /></el-icon>
                <div class="el-upload__text">
                  拖拽文件至此或 <em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">jpg 文件，大小不超过 10mb</div>
                </template>
              </el-upload>
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
              <el-button type="primary" @click="submitUpload"
                >上传图片</el-button
              >
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>

      <!-- 新增筛选栏 -->
      <div class="filter-bar">
        <el-select
          v-model="selectedCategory"
          placeholder="选择分类"
          @change="fetchPhotos"
          style="margin-right: 15px"
        >
          <el-option
            v-for="item in filterCategories"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-select
          v-model="selectedSort"
          placeholder="排序方式"
          @change="fetchPhotos"
        >
          <el-option label="最新" value="time" />
          <el-option label="最热" value="likes" />
        </el-select>
      </div>

      <!-- 瀑布流图片展示 -->
      <div class="photo-list">
        <div
          v-for="(photo, index) in photos"
          :key="photo.photo_id || index"
          class="photo-item"
        >
          <el-card class="photo-card" :body-style="{ padding: '0' }">
            <el-image
              :src="photo.url"
              lazy
              fit="cover"
              class="photo-image"
              :preview-src-list="[photo.url]"
            />
            <div class="photo-info">
              <span class="photo-title">{{ photo.title }}</span>
              <span class="photo-category">{{ photo.category }}</span>
            </div>
            <div class="photo-actions">
              <el-button
                size="mini"
                type="text"
                class="like-button"
                @click="likePhoto(photo.photo_id)"
              >
                <el-icon><Medal /></el-icon>
                <span class="likes-count">{{ photo.likes }} Likes</span>
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { uploadPhoto } from "../../api/api.js";
import { useRouter } from "vue-router";
import PhotoListBG from "../../components/PhotoListBG.vue";

const router = useRouter();

export default {
  components: {
    PhotoListBG, // 注册组件
  },
  data() {
    return {
      photos: [], // 图片数据
      fileList: [], // 已选择的文件列表
      uploadForm: {
        title: "",
        category: "",
      },
      categories: [
        { label: "自然", value: "Nature" },
        { label: "动物", value: "Animal" },
        { label: "人像", value: "Portrait" },
        { label: "纪实", value: "Documentary" },
        { label: "车辆", value: "Vehicle" },
        { label: "其他", value: "Item" },
      ],
      showUploadDialog: false, // 控制弹窗显示状态
      dialogImageUrl: "", // 预览图片的 URL
      dialogVisible: false, // 控制预览弹窗显示状态

      selectedCategory: "all", // 当前选中的分类
      selectedSort: "time", // 当前排序方式
      filterCategories: [
        // 筛选分类选项（包含"全部"）
        { label: "全部", value: "all" },
        { label: "自然", value: "Nature" },
        { label: "动物", value: "Animal" },
        { label: "人像", value: "Portrait" }, // 修正拼写错误（原Protrait->Portrait）
        { label: "纪实", value: "Documentary" },
        { label: "车辆", value: "Vehicle" },
        { label: "其他", value: "Item" },
      ],
    };
  },
  methods: {
     // 新增统一认证检查方法
    checkAuth() {
      if (!this.$store.state.user_id) {
        this.$router.push("/user/login");
        this.$message.error("登录状态失效，请重新登录！");
        return false;
      }
      return true;
    },

    // 自定义上传逻辑
    async beforeUpload(file) {
      // 上传前检查认证
      if (!this.checkAuth()) return false;

      // 1.设置允许上传的文件类型
      const validImageFormats = ["jpg"];
      const fileFormat = file.name.split(".").pop().toLowerCase();
      if (!validImageFormats.includes(fileFormat)) {
        this.$message.error("图片格式必须为 jpg/jpeg/png！");
        return false;
      }

      // 2.检查文件大小限制（10MB）
      const isLt10MB = file.size / 1024 / 1024 < 10;
      if (!isLt10MB) {
        this.$message.error("上传文件大小不能超过 10MB！");
        return false;
      }

      // 3.限制只能上传一张图片
      if (this.fileList.length > 1) {
        this.$message.error("只能上传一张图片！");
        return false;
      }

      // 4.为了实现预览功能，将文件对象转换为临时 URL，并推入 fileList (由handleChange方法处理)

      // 图片成功选择后返回true
      return true;
    },

    handleChange(file, fileList) {
      // 确保只保留最新的文件
      this.fileList = fileList.slice(-1);

      if (fileList.length > 1) {
        this.$message.error("已经选择了一张图片！");
        return;
      }

      this.fileList = fileList.map((item) => ({
        name: item.name,
        url: item.url || URL.createObjectURL(item.raw),
        raw: item.raw,
        uid: Date.now(), // 唯一标识，防止重复
      }));
    },

    handlePreview(uploadFile) {
      if (!uploadFile.url) {
        this.$message.error("无法预览图片！");
        return;
      }
      this.dialogImageUrl = uploadFile.url;
      this.dialogVisible = true;
    },

    // 提交上传
    async submitUpload() {
      // 添加认证检查
      if (!this.checkAuth()) return;

      if (!this.fileList.length) {
        this.$message.error("请先选择文件！");
        return;
      }
      if (this.fileList.length > 1) {
        this.$message.error("选中的文件数量不能超过 1 个！");
        return;
      }

      if (this.$store.state.user_id === null) {
        // 如果状态没有加载，跳转到登录页面
        router.push("/user/login"); // 跳转到登录页面
        this.$message.error("登录状态失效，请重新登录！");
        return; // 防止继续执行后续代码
      }
      const userId = this.$store.state.user_id; // 获取用户ID
      if (userId == null) {
        this.$message.error("请先登录！");
        console.error("uploadPhoto: user_id is null");
        return;
      }

      // 构建 FormData 对象
      const formData = new FormData();
      formData.append("image", this.fileList[0].raw); // 每次只上传一个文件
      formData.append("title", this.uploadForm.title);
      formData.append("category", this.uploadForm.category);
      formData.append("user_id", userId);

      try {
        // 调用上传接口
        const response = await uploadPhoto(formData);
        if (response.status === 200) {
          this.$message.success("图片上传成功！");
          this.fetchPhotos(); // 刷新图片列表
          this.handleDialogClose(); // 自动关闭弹窗
        } else {
          this.$message.error("上传失败，请重试！");
        }
      } catch (error) {
        console.error("上传错误：", error);
        this.$message.error("上传失败！");
      }
    },

    // 关闭弹窗时的处理逻辑
    handleDialogClose() {
      this.showUploadDialog = false;
      this.fileList = [];
      this.uploadForm.title = "";
      this.uploadForm.category = "";
    },

    // 修改 fetchPhotos 方法
    async fetchPhotos() {
      try {
        // 添加认证检查
        if (!this.checkAuth()) return;

        // 捕获分类值非法情况
        const validCategories = [
          "Nature",
          "Animal",
          "Portrait",
          "Documentary",
          "Vehicle",
          "Item",
        ];
        if (
          !validCategories.includes(this.selectedCategory) &&
          this.selectedCategory !== "all"
        ) {
          this.$message.error("无效分类参数");
          return;
        }

        let apiUrl = "";
        // 构造基础路径
        if (this.selectedCategory === "all") {
          apiUrl = "/photos";
        } else {
          // 必须严格匹配后端定义的大小写（如 Portrait）
          apiUrl = `/photos/category/${encodeURIComponent(this.selectedCategory)}`;
        }

        // 强制拼接排序参数
        apiUrl += `?sort=${this.selectedSort}`;

        const response = await this.$axios.get(apiUrl);
        this.photos = response.data.map((photo) => ({
          ...photo,
          url: photo.url,
        }));
      } catch (error) {
        console.error("获取图片失败:", error);
        this.$message.error("数据加载失败");
      }
    },

    // 点赞功能
    likePhoto(photoId) {
      // 添加认证检查
      if (!this.checkAuth()) return;

      if (this.$store.state.user_id === null) {
        // 如果状态没有加载，跳转到登录页面
        router.push("/user/login"); // 跳转到登录页面
        this.$message.error("登录状态失效，请重新登录！");
        return; // 防止继续执行后续代码
      }
      const formData = new FormData();
      formData.append("user_id", this.$store.state.user_id);

      this.$axios
        .post(`/photos/${photoId}/like`, formData)
        .then(() => {
          this.$message({
            message: "点赞成功！",
            type: "success",
          });
          this.fetchPhotos();
        })
        .catch((error) => {
          console.error("Error:", error.response ? error.response.data : error);
        });
    },
  },
  mounted() {
    this.checkAuth() && this.fetchPhotos();
  },
};
</script>


<style scoped>
/* 上传图片容器 */
.upload-container {
  display: flex;
  justify-content: center;
  margin-top: 0px;
  margin-bottom: 10px;
  box-shadow: 0 2px 6px rgba(255, 182, 193, 0.3); /* 粉色系阴影 */
  border-radius: 8px;
}

.upload-container {
  background: linear-gradient(
    45deg,
    #ffc1cb,
    /* 浅粉红 */ #ffc7d0,
    /* 粉红 */ #ffe4e1 /* 粉白 */
  );
  background-size: 200% 200%;
  animation: gradientFlow 4s ease infinite;
  position: relative;
}

/* 添加高光粒子层 */
.upload-container::after {
  content: "";
  position: absolute;
  inset: 0;
  background: radial-gradient(
    circle,
    rgba(255, 255, 255, 0.3) 15%,
    transparent 70%
  );
  mix-blend-mode: overlay;
  pointer-events: none; /* 该层忽略点击事件 */
}

@keyframes gradientFlow {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

/* 深度覆盖上传框的样式 */
.custom-upload-box::v-deep(.el-upload-dragger) {
  width: 100%;
  height: 100%;
  border-radius: 0px;
  border: 1px dashed #d3d3d3;
  background-color: #f9f9f9;
}

/* 筛选容器 - 光效增强 */
.filter-bar {
  padding: 20px;
  background: linear-gradient(135deg, #fff9e6 0%, #ffffff 100%);
  border-radius: 18px;
  box-shadow: 
    0 8px 32px rgba(255,215,0,0.25),
    inset 0 2px 4px rgba(255,255,255,0.5);
  margin: 24px 0;
  position: relative;
  overflow: hidden;
  perspective: 800px;
}

/* 双流光效 */
.filter-bar::before,
.filter-bar::after {
  content: '';
  position: absolute;
  width: 300%;
  height: 200%;
  animation: flowLight 2s linear infinite;
  mix-blend-mode: overlay;
  opacity: 0.6;
}

.filter-bar::before {
  background: repeating-linear-gradient(
    45deg,
    rgb(255, 176, 176) 0%,
    rgba(255, 135, 135, 0.993) 15%,
    transparent 30%
  );
  transform: rotate(45deg) translate(-20%, -20%);
}

.filter-bar::after {
  background: repeating-linear-gradient(
    -45deg,
    #ffec72f5 0%,
    rgb(236, 255, 28) 15%,
    transparent 30%
  );
  animation-delay: -2s;
  transform: rotate(-45deg) translate(20%, 20%);
}

@keyframes flowLight {
  0% { transform: translate(-30%, -30%); }
  100% { transform: translate(30%, 30%); }
}

/* 选择器核心样式 */
:deep(.custom-sort-select .el-select__wrapper) {
  background: linear-gradient(145deg, #fff3d9 0%, #fff9ec 100%) !important;
  border: 2px solid #ffd700 !important;
  border-radius: 14px;
  box-shadow: 
    0 6px 20px rgba(255,215,0,0.3),
    inset 0 2px 4px rgba(255,255,255,0.5),
    inset 0 -2px 4px rgba(255,215,0,0.1);
  transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
  transform: perspective(600px) rotateX(3deg) translateZ(20px);
  min-height: 48px;
}

/* 悬停动效 */
:deep(.custom-sort-select:hover .el-select__wrapper) {
  transform: 
    perspective(600px) 
    rotateX(-5deg)
    translateZ(40px)
    scale(1.05);
  border-color: #ffa500 !important;
  box-shadow: 
    0 10px 40px rgba(255,165,0,0.4),
    inset 0 3px 6px rgba(255,255,255,0.6);
  background: linear-gradient(145deg, #ffeec8 0%, #fff6e0 100%) !important;
}

/* 焦点状态流光 */
@keyframes borderGlow {
  0% { 
    border-color: #ffd700;
    box-shadow: 0 0 15px rgba(255,215,0,0.5);
  }
  50% { 
    border-color: #ff6b6b;
    box-shadow: 0 0 25px rgba(255,107,107,0.7);
  }
}

:deep(.custom-sort-select.is-focused .el-select__wrapper) {
  animation: borderGlow 1.2s infinite;
}

/* 下拉面板 */
:deep(.custom-sort-select .el-select__dropdown) {
  border: none;
  border-radius: 14px;
  box-shadow: 
    0 15px 50px rgba(255,215,0,0.3),
    inset 0 2px 4px rgba(255,255,255,0.4);
  transform-origin: top center;
  transition: 
    transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1),
    opacity 0.25s ease;
}

:deep(.custom-sort-select .el-select__dropdown.is-enter-active) {
  opacity: 0;
  transform: 
    scale(0.95) 
    translateY(-20px)
    rotateX(-15deg);
}

/* 选项立体效果 */
:deep(.custom-sort-select .el-select-dropdown__item) {
  padding: 14px 24px;
  font-size: 16px;
  color: #2c3e50;
  background: rgba(255,255,255,0.95);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  transform: translateZ(0);
  border-bottom: 1px solid rgba(255,215,0,0.1);
}

:deep(.custom-sort-select .el-select-dropdown__item:hover) {
  background: linear-gradient(145deg, #fff3e0 0%, #ffe4b3 100%);
  transform: 
    translateX(15px)
    translateZ(30px);
  box-shadow: 
    4px 6px 20px rgba(255,165,0,0.15),
    inset 2px 2px 4px rgba(255,255,255,0.3);
}

:deep(.el-select-dropdown__item.is-selected) {
  background: linear-gradient(145deg, 
    rgba(255,235,205,0.9) 0%,
    rgba(255,215,0,0.7) 100%
  );
  color: #d35400;
  transform: translateZ(40px);
}

/* 高光反射层 */
:deep(.el-select__wrapper::after) {
  content: '';
  position: absolute;
  top: -15%;
  left: -15%;
  width: 130%;
  height: 130%;
  background: radial-gradient(
    circle at 50% 30%, 
    rgba(255,255,255,0.6) 0%, 
    rgba(255,228,132,0.3) 50%,
    transparent 80%
  );
  mix-blend-mode: overlay;
  animation: highlightFlow 6s linear infinite;
  pointer-events: none;
}

@keyframes highlightFlow {
  0% { transform: translate(-10%, -10%); }
  50% { transform: translate(10%, 10%); }
  100% { transform: translate(-10%, -10%); }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .filter-bar {
    padding: 16px;
    margin: 16px 0;
    border-radius: 14px;
    perspective: 400px;
  }

  :deep(.custom-sort-select .el-select__wrapper) {
    min-height: 52px;
    padding: 12px 16px;
    font-size: 15px;
    transform: perspective(400px) translateZ(10px);
  }

  :deep(.custom-sort-select:hover .el-select__wrapper) {
    transform: 
      perspective(400px)
      translateZ(20px)
      scale(1.03);
  }

  :deep(.el-select-dropdown__item) {
    padding: 12px 18px;
    font-size: 15px;
  }

  /* 简化移动端动画 */
  @keyframes flowLight {
    0% { transform: translate(-15%, -15%); }
    100% { transform: translate(15%, 15%); }
  }
}

/* 瀑布流布局容器 */
.photo-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); /* 适配宽度 */
  gap: 16px; /* 图片间距 */
  padding: 20px;
}

/* 每个图片项 */
.photo-item {
  width: 100%;
}

/* 图片卡片 */
.photo-card {
  position: relative;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

/* 图片 */
.photo-image {
  width: 100%;
  height: 300px;
  object-fit: cover; /* 保证图片按比例适配 */
  border-radius: 8px 8px 0 0;
}

/* 图片信息栏 */
.photo-info {
  padding: 10px;
  background: #c2e2f9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
}

/* 点赞功能栏 */
.photo-actions {
  position: absolute;
  bottom: 0px;
  right: 80px;
  display: flex;
  align-items: center;
  gap: 10px;
  background: rgba(245, 112, 192, 0.6);
  padding: 3px 6px;
  border-radius: 8px;
}

.likes-count {
  font-size: 12px;
}

.like-button {
  font-size: 16px;
  color: #a70000;
}
</style>
